﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TaskKernel.Configuration;
using TaskKernel.DTO;
using TaskKernel.Domain;
using TaskWebApplicationUI.PresenterLayer;
using File = TaskKernel.Domain.File;

namespace TaskWebApplicationUI
{
    public interface ICreateTaskView : IAbstractView
    {
        IList<UniversalModelDDL> Participants { set; get; }
        IList<ParticipantsModelDDL> ChangedParticipants { set; get; }
        IList<UniversalModelDDL> Departments { set; }
        IList<UniversalModelDDL> Executors { set; }
        IList<UniversalModelDDL> Users { set; }
        UniversalModelDDL DeletedParticipant { get; set; }
        string HistoryEntryText { get; set; }
        DateTime? ExpirationDate { set; get; }
        string UsersSearchString { get; }
        Guid SelectedExecutor { set; get; }
        Guid SelectedDepartment { set; get; }
        Guid SelectedUser { get; }
        int Priority { set; get; }
        string TaskName { set; get; }
        string Tag { set; get; }
        Guid TaskID { set; get; }
        string RedirectWebPath { set; get; }
        string ErrorMessage { set; }
        string IPAddress { get; }
        string ReminderNote { get; set; }
        bool ReminderEnable { get; set; }
        IList<File> Filez { get; set; }
        Permissions RolePermissions { set; }
    }

    public partial class CreateTaskView : ViewPage<ICreateTaskView, CreateTaskPresenter>, ICreateTaskView
    {
        private UniversalModelDDL deletedParticipant;
        private IList<File> files = new List<File>();

        #region ICreateTaskView Members

        public string DepartmentName
        {
            set { Department.Text = value; }
        }

        public IList<File> Filez
        {
            get
            {
                var fileSize = long.Parse(ConfigurationManager.AppSettings["maxFileSize"]);
                for (var i = 0; i < Request.Files.Count; i++){
                    if (String.IsNullOrEmpty(Request.Files[i].FileName)) continue;
                    var stream = Request.Files[i].InputStream;
                    if (stream.Length >= fileSize || stream.Length <= 0) continue;
                    var buffer = Tools.ReadFully(stream);
                    files.Add(new File(Path.GetFileName(Request.Files[i].FileName), buffer, Tools.GetMD5HashCode(buffer)));
                }
                return files;
            }
            set { files = value; }
        }

        public Permissions RolePermissions
        {
            set
            {
                PrioritiesDDL.Enabled = value.Priority;
                BtnAddComment.Enabled = value.Save;
                ExecutorsDDL.Enabled = value.Executors;
                DepartmentsDDL.Enabled = value.Department;
            }
        }

        public string IPAddress
        {
            get
            {
                return
                    HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
        }

        public string ErrorMessage
        {
            set { ErrorMessageLabel.Text = value; }
        }

        public string ReminderNote { get; set; }
        public bool ReminderEnable { get; set; }
        public string ReminderDate { get; set; }
        public int ReminderHours { get; set; }
        public int ReminderMinutes { get; set; }

        public string TaskName
        {
            get { return TaskNameTB.Text; }
            set { }
        }

        public string Tag { get; set; }

        public Guid TaskID
        {
            get
            {
                if (ViewState["TaskID"] == null) return Guid.Empty;
                return (Guid) ViewState["TaskID"];
            }
            set { ViewState["TaskID"] = value; }
        }

        public IList<UniversalModelDDL> Executors
        {
            set
            {
                ExecutorsDDL.DataSource = value;
                ExecutorsDDL.DataBind();
            }
        }

        public IList<UniversalModelDDL> Departments
        {
            set
            {
                DepartmentsDDL.DataSource = value;
                DepartmentsDDL.DataBind();
            }
        }

        public Guid SelectedDepartment
        {
            set
            {
                DepartmentsDDL.ClearSelection();
                DepartmentsDDL.Items.FindByValue(value.ToString()).Selected = true;
            }
            get { return new Guid(DepartmentsDDL.SelectedItem.Value); }
        }

        public IList<UniversalModelDDL> Users
        {
            set
            {
                UsersDDL.DataSource = value;
                UsersDDL.DataTextField = "Name";
                UsersDDL.DataValueField = "ID";
                UsersDDL.DataBind();
            }
        }

        public IList<UniversalModelDDL> Participants
        {
            set
            {
                ViewState["Participants"] = value;
                ParticipantsGridView.DataSource = value;
                ParticipantsGridView.DataBind();
            }
            get { return (IList<UniversalModelDDL>) ViewState["Participants"]; }
        }

        public IList<ParticipantsModelDDL> ChangedParticipants
        {
            get
            {
                if (ViewState["ChangedParticipants"] == null) return new List<ParticipantsModelDDL>();
                return (IList<ParticipantsModelDDL>) ViewState["ChangedParticipants"];
            }
            set { ViewState["ChangedParticipants"] = value; }
        }

        public Guid SelectedUser
        {
            get
            {
                if (UsersDDL.SelectedItem != null)
                    return new Guid(UsersDDL.SelectedItem.Value);
                return Guid.Empty;
            }
        }

        public int Priority
        {
            set
            {
                PrioritiesDDL.ClearSelection();
                PrioritiesDDL.Items.FindByValue(value.ToString(CultureInfo.InvariantCulture)).Selected = true;
            }
            get { return Int32.Parse(PrioritiesDDL.SelectedItem.Value); }
        }

        public Guid SelectedExecutor
        {
            set
            {
                ExecutorsDDL.ClearSelection();
                ExecutorsDDL.Items.FindByValue(value.ToString()).Selected = true;
            }
            get { return new Guid(ExecutorsDDL.SelectedItem.Value); }
        }

        public string HistoryEntryText
        {
            get { return Editor.Text; }
            set { Editor.Text = value; }
        }

        public string UsersSearchString
        {
            get { return UsersSearchTB.Text; }
        }

        public UniversalModelDDL DeletedParticipant
        {
            get { return deletedParticipant; }
            set { deletedParticipant = value; }
        }

        public DateTime? ExpirationDate
        {
            get { return (DateTime?)dxExpirationDate.Value; }
            set { dxExpirationDate.Value = value; }

        }


        public string RedirectWebPath { get; set; }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            Editor.BasePath = GetBasePath() + TaskKernelConfiguration.EditorPath;
            if (!Page.IsPostBack)
                Presenter.OnViewInitialized();
        }

        protected void ParticipantSearch_TextChanged(object sender, EventArgs e)
        {
            Presenter.OnSearchParticipant();
        }

        protected void ParticipantsView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            FillDeletedParticipant(e);
            Presenter.OnDelParticipant();
        }

        private void FillDeletedParticipant(GridViewDeleteEventArgs e)
        {
            var IndexOfDeletedParticipant = e.RowIndex;
            const int ColumnWithFullName = 0;
            var row = ParticipantsGridView.Rows[IndexOfDeletedParticipant];
            var id = (Guid)ParticipantsGridView.DataKeys[IndexOfDeletedParticipant].Values["ID"];
            deletedParticipant = new UniversalModelDDL(id, row.Cells[ColumnWithFullName].Text);
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            Presenter.OnAddParticipant();
        }

        protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
        {
            Presenter.OnSave();
            if (TaskID != Guid.Empty)
            {
                var link = RedirectWebPath + TaskKernelConfiguration.SuffixPath + TaskKernelConfiguration.SeparatorPath + TaskKernelConfiguration.EditPage + TaskID;
                Response.Redirect(link);
            }
        }
    }
}